import React, { useState, useEffect } from 'react';
import { Tabs, Spin, Empty, List } from 'antd';
import moment from 'moment';
import { history } from 'umi'
import LinkTo from '@/components/LinkTo';
import { getAuditedList, getReadList, getWaitApprovalList } from '@/services/notice/homePage';
import authHelpr from '@/utils/auth/helper';
import { eventTrack } from '@/utils/track';

import { MoreBar } from '../common/TabBarExtraContent';
import styles from '../../homepage.less';

const { TabPane } = Tabs;
const { checkCode } = authHelpr;
/**
 * 我的流程
 */
const Wdlc = props => {
    // 获取登陆人公司postid
    const user = localStorage.getItem('user');
    const { employeeCode, firstOrgInfo } = user ? JSON.parse(user) : {};
    const { responders } = props;
    const { droppableProps, onAdd } = responders;

    const [spinning, setSpinning] = useState(false);
    const [approveData, setApproveData] = useState([]);
    const [passData, setPassData] = useState([]);
    const [readData, setReadData] = useState([]);
    const [approveTotal, setApproveTotal] = useState(0);
    // const [passTotal, setPassTotal] = useState(0);
    const [readTotal, setReadTotal] = useState(0);
    const tabs = [
        {
            name: `待我审批 (${approveTotal})`,
            code: 'portal:newmyflow:approvelist',
            component: item => (
                <List.Item key={item.title}>
                    {/* 待我审批 */}
                    <List.Item.Meta
                        className={styles.workListMeta}
                        title={
                            <LinkTo
                                onClick={(e, url) => {
                                    eventTrack({
                                        eventName: 'portal_flow_new_wait_approval_click',
                                        pageName: 'personal_portal',
                                        eventProps: {
                                            click_context: item.processInstanceName
                                        }
                                    });
                                    history.push(url);
                                }}
                                to="/personal/portal/waitApproval/approvalDetail"
                                query={{
                                    processInstanceName: item.processInstanceName,
                                    taskId: item.taskId,
                                    createUser: item.createUser
                                }}
                            >
                                {item.processInstanceName}
                            </LinkTo>
                        }
                    />
                    <div className={styles.wnlist_time}>
                        {droppableProps['data-rbd-droppable-id'] === 'droppable'
                            ? moment(item.startTime).format('YYYY-MM-DD HH:mm')
                            : moment(item.startTime).format('YYYY-MM-DD')}
                    </div>
                </List.Item>
            ),
            path: '/personal/portal/waitApproval/list',
            dataSource: approveData
        },
        {
            // name: `经我审批 (${passTotal})`,
            name: '经我审批',
            code: 'portal:newmyflow:passmelist',
            component: item => (
                <List.Item key={item.companyId}>
                    <List.Item.Meta
                        className={styles.workListMeta}
                        title={
                            <LinkTo
                                onClick={(e, url) => {
                                    eventTrack({
                                        eventName: 'portal_flow_new_my_audited_info_click',
                                        pageName: 'personal_portal',
                                        eventProps: {
                                            click_context: item.processInstanceName
                                        }
                                    });
                                    history.push(url);
                                }}
                                to="/personal/portal/myAudited/myAuditedDetail"
                                query={{
                                    processInstanceName: item.processInstanceName,
                                    processInstanceId: item.processInstanceId,
                                    taskId: item.taskId
                                }}
                            >
                                {item.processInstanceName}
                            </LinkTo>
                        }
                    />
                    <div className={styles.wnlist_time}>
                        {droppableProps['data-rbd-droppable-id'] === 'droppable'
                            ? moment(item.startTime).format('YYYY-MM-DD HH:mm')
                            : moment(item.startTime).format('YYYY-MM-DD')}
                    </div>
                </List.Item>
            ),
            path: '/personal/portal/myAudited/list',
            dataSource: passData
        },
        {
            name: `抄送我的 (${readTotal})`,
            code: 'portal:newmyflow:cclist',
            component: item => (
                <List.Item key={item.id}>
                    <List.Item.Meta
                        className={styles.workListMeta}
                        title={
                            <LinkTo
                                onClick={(e, url) => {
                                    eventTrack({
                                        eventName: 'portal_flow_new_my_audit_read_info_click',
                                        pageName: 'personal_portal',
                                        eventProps: {
                                            click_context: item.processInstanceName
                                        }
                                    });
                                    history.push(url);
                                }}
                                to="/personal/portal/myAuditRead/myAuditReadDetail"
                                query={{
                                    applicationNo: item.applicationNo,
                                    processInstanceId: item.processInstanceId,
                                    id: item.id,
                                    readFlag: item.readFlag,
                                    processInstanceName: item.processInstanceName
                                }}
                            >
                                {item.processInstanceName}
                            </LinkTo>
                        }
                    />
                    <div className={styles.wnlist_time}>
                        {droppableProps['data-rbd-droppable-id'] === 'droppable'
                            ? moment(item.startTime).format('YYYY-MM-DD HH:mm')
                            : moment(item.startTime).format('YYYY-MM-DD')}
                    </div>
                </List.Item>
            ),
            path: '/personal/portal/myAuditRead/list',
            dataSource: readData
        }
    ];

    const moreEventHandler = (e, url) => {
        eventTrack({
            eventName: 'portal_flow_new_more_click',
            pageName: 'personal_portal'
        });
        history.push(url);
    };

    const hasAuth = tabs.filter(item => checkCode(item.code));
    const [linkProps, setLinkProps] = useState({
        to: hasAuth.length > 0 ? hasAuth[0].path : '',
        query: {},
        onClick: moreEventHandler
    });
    /* 是否全部没有权限 */
    const isAllNone = hasAuth.length === 0;
    // 切换面板-改变更多的跳转路径
    const activeTab = code => {
        const find = tabs.find(item => item.code === code) || {};
        setLinkProps({
            to: find.path,
            query: {},
            onClick: moreEventHandler
        });
    };
    const init = async () => {
        if (isAllNone) {
            return;
        }
        const { firstCompanyCode: organizationCode } = firstOrgInfo;
        setSpinning(true);
        const [read, pass, approve] = await Promise.all([
            getReadList({
                pageNo: 1,
                pageSize: 4,
                employeeCode,
                organizationCode,
                readFlag: 0
            }),
            getAuditedList({ pageNo: 1, pageSize: 4, employeeCode, organizationCode }),
            getWaitApprovalList({
                pageNo: 1,
                pageSize: 4,
                employeeCode,
                organizationCode
            })
        ]);
        setSpinning(false);
        if (read && read.code === 10000) {
            setReadData(read.data.rows);
            setReadTotal(read.data.total);
        }
        if (pass && pass.code === 10000) {
            setPassData(pass.data.rows);
            // setPassTotal(pass.data.total);
        }
        if (approve && approve.code === 10000) {
            setApproveData(approve.data.rows);
            setApproveTotal(approve.data.total);
        }
    };
    useEffect(() => {
        init();
    }, []);
    return (
        <Spin spinning={spinning}>
            {isAllNone ? (
                <div>
                    <div className={styles.wnNoticeTitle}>
                        <h4>我的流程</h4>
                    </div>
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                </div>
            ) : (
                <Tabs
                    className={styles.wnWdlcTitle}
                    onChange={activeTab}
                    onTabClick={key => {
                        const eventMap = {
                            'portal:newmyflow:approvelist': 'portal_flow_new_wait_approval_click',
                            'portal:newmyflow:passmelist': 'portal_flow_new_my_audited_click',
                            'portal:newmyflow:cclist': 'portal_flow_new_my_audit_read_click'
                        };
                        eventTrack({
                            eventName: eventMap[key],
                            pageName: 'personal_portal'
                        });
                    }}
                    defaultActiveKey="approve"
                    tabBarExtraContent={<MoreBar linkProps={linkProps} onAdd={onAdd} isDelete={false} />}
                >
                    {hasAuth.map(item => (
                        <TabPane tab={item.name} key={item.code}>
                            <List
                                className={styles.wnlist}
                                itemLayout="horizontal"
                                split={false}
                                dataSource={item.dataSource.filter((newItem, index) => index < 4)}
                                renderItem={item.component}
                            />
                        </TabPane>
                    ))}
                </Tabs>
            )}
        </Spin>
    );
};
export default Wdlc;
